#include "VisualiserDialog.h"
#include "ui_Visualiser.h"
#include "PreprocessedFile.h"
#include <qmessagebox.h>
#include <qfiledialog.h>

VisualiserDialog::VisualiserDialog(QWidget *parent, Loader * pLoader, Analyser * pAnalyser)
    : QDialog(parent), ui(new Ui::VisualiserDialog)
{
    ui->setupUi(this);

    // Copying the data from loader

    if ( pLoader )
    {
        m_cameras = pLoader->getCameras();
        m_point_cloud = pLoader->getPointCloud();

        ui->renderWidget->setCameraList(&m_cameras);
        ui->renderWidget->setPointCloud(&m_point_cloud);
        ui->renderWidget->updateOrigin();
    }

    if(pAnalyser)
    {
        m_cameras = pAnalyser->getCameras();
        m_point_cloud = pAnalyser->getPointCloud();

        ui->renderWidget->setPointCloud(&m_point_cloud);
        ui->renderWidget->setCameraList(&m_cameras);
        ui->renderWidget->updateOrigin();
    }

    for(int i=0; i < m_cameras.size(); i++)
    {
        ui->listWidget->addItem(m_cameras[i].getFilename());
    }

    connect(ui->listWidget, SIGNAL(itemSelectionChanged()), this, SLOT(updateImageView()));
}

void VisualiserDialog::updateImageView()
{

    int index = ui->listWidget->row(ui->listWidget->selectedItems().at(0));
    QString name = m_cameras[index].getFilename();

    QImage image;

    if ( image.load(name) )
    {
        ui->sampleImage->setImage(image);
    }

    ui->renderWidget->setCameraSelection(index);
    //ui->renderWidget->resetRotation();
    ui->renderWidget->update();

}

VisualiserDialog::~VisualiserDialog()
{
    delete ui;
}

void VisualiserDialog::closeEvent(QCloseEvent * event)
{
    // ask whether this needs to be saved to a preprocessed file
    QMessageBox msgBox;

    msgBox.setText("Do you want to save the processed data to a file?");
    msgBox.setInformativeText("Stored processed data file can be opened later with this program which will be faster for loading.");
    msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Close);

    int result = msgBox.exec();

    if ( result == QMessageBox::Save )
    {
        QFileDialog dialog(this);
        dialog.setAcceptMode(QFileDialog::AcceptSave);
        dialog.setNameFilter(tr("Preprocessed Object Point File (*.pop)"));
        dialog.setViewMode(QFileDialog::Detail);
        dialog.setFileMode(QFileDialog::AnyFile);

        if (dialog.exec())
        {
            if ( dialog.selectedFiles().size() > 0 )
            {
                PreprocessedFile file;
                file.setCameras(m_cameras);
                file.setPointCloud(m_point_cloud);

                file.save(dialog.selectedFiles().at(0));
            }
        }
    }
}
